package com.akk.utils;

import org.apache.commons.codec.digest.DigestUtils;
import org.junit.Test;
import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.Date;

public class Md5Utils {




	/**
	 *
	 * @param text
	 * @param key
	 * @param charset
	 * @return 签名结果
	 */
	public static String sign(String text, String key, String charset) throws Exception {
		text = text + key;
		return DigestUtils.md5Hex(getContentBytes(text, charset));
	}

	/**
	 * @param text
	 * @param sign
	 * @param key
	 * @param charset
	 * @return 签名结果
	 */
	public static boolean verify(String text, String sign, String key, String charset) throws Exception {
		text = text + key;
		String mysign = DigestUtils.md5Hex(getContentBytes(text, charset));
		if (mysign.equals(sign)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * @param content
	 * @param charset
	 * @return
	 * @throws SignatureException
	 * @throws UnsupportedEncodingException
	 */
	private static byte[] getContentBytes(String content, String charset) {
		if (charset == null || "".equals(charset)) {
			return content.getBytes();
		}
		try {
			return content.getBytes(charset);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("签名过程中出现错,指定的编码集不对,您目前指定的编码集是:" + charset);
		}
	}
	public static String md5_(String str){
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		BASE64Encoder encoder = new BASE64Encoder();
		String newstr = null;
		try {
			newstr = encoder.encode(md5.digest(str.getBytes("utf-8")));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return newstr;
	}


	public static String md5_low(String text){

		try {
			MessageDigest digest = MessageDigest.getInstance("md5");
			byte[] result = digest.digest(text.getBytes());
			StringBuilder sb =new StringBuilder();
			for(byte b:result){
				int number = b&0xff;
				String hex = Integer.toHexString(number);
				if(hex.length() == 1){
					sb.append("0"+hex);
				}else{
					sb.append(hex);
				}
			}
			return sb.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		return "" ;
	}

	@Test
	public void test() {
		long timestamp = new Date().getTime();
		System.out.println(timestamp);
		System.out.println(md5_low("123456"));
		//System.out.println(UUID.randomUUID().toString().hashCode());
		System.out.println(md5_low(md5_low(""+timestamp+"%aikaka2017")));
		//System.out.println(md5_low(md5_low("ee706d65-96db-41da-a715-1e904fe0b255"+"1497506687637"+"aikaka2017")));
	}

}
